package com.lahuan.config.datasource;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源配置
 */
@Configuration
public class DataSourceConfig {
    /**
     * 主
     */
    public static final String MAIN = "main";
    /**
     * 从
     */
    public static final String SLAVE1 = "slave1";
    /**
     * 从
     */
    public static final String SLAVE2 = "slave2";
    /**
     * 保存所有的从库,路由用
     */
    public static final String[] SLAVE_LIST = new String[]{SLAVE1, SLAVE2};

    @Bean(name =DataSourceConfig.MAIN )
    @ConfigurationProperties(prefix = "spring.datasource.main")
    public DataSource dataSourceMain() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = DataSourceConfig.SLAVE1)
    @ConfigurationProperties(prefix = "spring.datasource.slave1")
    public DataSource dataSourceSlave1() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = DataSourceConfig.SLAVE2)
    @ConfigurationProperties(prefix = "spring.datasource.slave2")
    public DataSource dataSourceSlave2() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 动态数据源
     */
    @Primary
    @Bean(name = "dynamicRoutingDataSource")
    public DataSource dynamicRoutingDataSource() {

        Map<Object, Object> all = new HashMap<>();
        all.put(DataSourceConfig.MAIN, dataSourceMain());
        all.put(DataSourceConfig.SLAVE1, dataSourceSlave1());
        all.put(DataSourceConfig.SLAVE2, dataSourceSlave2());
        DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();
        dynamicRoutingDataSource.setDefaultTargetDataSource(dataSourceMain());
        dynamicRoutingDataSource.setTargetDataSources(all);
        return dynamicRoutingDataSource;
    }

}